<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\User;
use App\Models\Withdraw;
use Illuminate\Http\Request;

class WithdrawController extends BaseController
{

    public function index(Request $request) {
        $merchant_id = $this->getUserId();
        $search = ['audit_status' => -1];
        $input = $request->input();
        $list = Withdraw::where('merchant_id', $merchant_id)->apply($search, $input)
            ->orderBy("id", "desc")
            ->paginate(per_page());
        return $this->paginate($list);
    }

    public function apply(Request $request) {
        $merchant = $this->getUser();
        if ($merchant->is_vip != 1 && $merchant->is_daren != 1)
            return $this->failed('非会员或者达人不能提现');
        $merchant_id = $merchant->id;
        $this->validate($request, [
            'amount' => 'required',
            'realname' => 'required',
            'alipay_account' => 'required'
        ]);
        $input = $request->input();
        $amount = \request('amount');
        if ($amount < 0.1)
            return $this->failed('最小金额0.1元');

        if (is_float($amount * 100)) {
            return $this->failed('小数点只支持2位');
        }

        if ($amount > 10000)
            return $this->failed('单日最多提现1万');

        $date = date('Y-m-d');
        $exist = Withdraw::where('merchant_id', $merchant_id)->where('date', $date)->exists();
        if ($exist)
            return $this->failed('今日已申请');

        $audit_exist = Withdraw::where('merchant_id', $merchant_id)->whereIn('status', [0, 1])->exists();
        if ($audit_exist)
            return $this->failed('存在未审批的单子');

        $amount_fen = $amount * 100;
        //一次性只能提取一次 ，不存在重合问题
        if ($amount_fen > $merchant->balance) {
            return $this->failed('提现金额大于账户余额');
        }

        $data = [
            'trade_no' => create_order_no('t'),
            'amount' => $amount_fen,
            'benefit_user' => User::BENEFIT_USER,
            'merchant_id' => $merchant_id,
            'date' => $date,
            'balance' => $merchant->balance,
            'realname' => $input['realname'],
            'alipay_account' => $input['alipay_account']
        ];
        Withdraw::create($data);
        return $this->success(['trade_no' => $data['trade_no']], '申请成功');
    }



}

